import React, { useState, useEffect, useDeferredValue } from "react";

const App = () => {
  const [text, setText] = useState("");
  const [list, setList] = useState([]);
  const [count, setCount] = useState(0);

  const handleChange = (e) => {
    setText(e.target.value);
  };

  // 类似于js的防抖
  // 当页面出现卡顿的时候，选择性地过滤调中间的显示过程
  const text2 = useDeferredValue(text);

  useEffect(() => {
    setCount((v) => v + 1);
    setTimeout(() => {
      const arr = [];
      for (let i = 0; i < 20000; i++) {
        arr.push({ id: i, value: text2 });
      }
      setList(arr);
    }, 500);
  }, [text2]);

  return (
    <>
      <h2>useDeferredValue</h2>
      <p>一共渲染了{count}次</p>

      <input type="text" value={text} onChange={handleChange} />

      <ul>
        {list.map((item) => (
          <li key={item.id}>{item.value}</li>
        ))}
      </ul>
    </>
  );
};

export default App;
